﻿using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;

namespace AccessControl.Wpf.Controls
{
	class DrawerButton : ToggleButton
	{
		#region Fields

		DispatcherTimer _timer;
		private static readonly Type s_ThisType = typeof(DrawerButton);

		#endregion

		#region Public Constructor

		public DrawerButton()
		{
			_timer = new DispatcherTimer()
			{
				Interval = TimeSpan.FromMilliseconds(20),
			};

			_timer.Tick += new EventHandler(OnTimerTick);
		}

		#endregion

		#region Dependency Properties

		public static readonly DependencyProperty AttachedControlProperty = DependencyProperty.Register(
			"AttachedControl",
			typeof(FrameworkElement),
			s_ThisType, 
			new PropertyMetadata(null));

		public static readonly DependencyProperty OpenedHeightProperty = DependencyProperty.Register(
			"OpenedHeight",
			typeof(double),
			s_ThisType,
			new PropertyMetadata(400.00));

		#endregion

		#region Public Properties

		public FrameworkElement AttachedControl
		{
			get { return (FrameworkElement)GetValue(AttachedControlProperty); }
			set { SetValue(AttachedControlProperty, value); }
		}

		public double OpenedHeight
		{
			get { return (double)GetValue(OpenedHeightProperty); }
			set { SetValue(OpenedHeightProperty, value); }
		}

		#endregion

		#region Protected Members

		protected override void OnChecked(RoutedEventArgs e)
		{
			base.OnChecked(e);

			/* Validate the attached control */
			if (AttachedControl == null)
				return;

			/* Start the timer */
			if (!_timer.IsEnabled)
				_timer.Start();
		}

		protected override void OnUnchecked(RoutedEventArgs e)
		{
			base.OnUnchecked(e);

			/* Validate the attached control */
			if (AttachedControl == null)
				return;

			/* Start the timer */
			if (!_timer.IsEnabled)
				_timer.Start();
		}

		void OnTimerTick(object sender, EventArgs e)
		{
			if (IsChecked.HasValue && IsChecked.Value)
			{
				if ((AttachedControl.Height + 50) <= OpenedHeight)
					AttachedControl.Height += 50;
				else
					AttachedControl.Height = OpenedHeight;

				if (AttachedControl.Height == OpenedHeight)
					_timer.Stop();
			}
			else
			{
				if ((AttachedControl.Height - 50) >= 0)
					AttachedControl.Height -= 50;
				else
					AttachedControl.Height = 0;

				if (AttachedControl.Height == 0)
					_timer.Stop();
			}
		}

		#endregion
	}
}
